package com.by.and_widget;

import android.content.Context;
import android.database.DataSetObserver;
import android.graphics.Point;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;


/**
 * 仿微信九宫格显示图片
 */
public class NineGridLayout extends ViewGroup {
    /**
     * 默认子view之间的间隔4dp
     */
    private static final int DEFAULT_SPACING = 4;
    /**
     * 默认3列
     */
    private static final int COLUMNS = 3;

    private BaseAdapter mAdapter;
    private AdapterView.OnItemClickListener mOnItemClickListener;
    private int spacing;
    private int columns;
    private int rows;
    private int itemWidth;
    private int itemHeight;

    public NineGridLayout(Context context) {
        super(context);
        init();
    }

    public NineGridLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        spacing = dpTpPx(DEFAULT_SPACING);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int resultWidth = 0;
        int resultHeight = 0;
        // 设置每一个Item的宽高
        itemWidth = (widthSize - spacing * (COLUMNS - 1)) / COLUMNS;
        itemHeight = itemWidth;
        getTableInfo();
        resultWidth = widthSize;
        if (heightMode == MeasureSpec.AT_MOST) {
            resultHeight = itemHeight * rows + spacing * (rows - 1);
        } else {
            resultHeight = heightSize;
        }
        if (getChildCount() == 1) {
            measureChildren(MeasureSpec.makeMeasureSpec(resultWidth, MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(resultHeight, MeasureSpec.AT_MOST));
        } else {
            measureChildren(MeasureSpec.makeMeasureSpec(itemWidth, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(itemHeight, MeasureSpec.EXACTLY));
        }
        Log.e("onMeasure", "width:" + resultWidth + ",height:" + resultHeight);
        setMeasuredDimension(resultWidth, resultHeight);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int childrenCount = getChildCount();
        if (childrenCount > 0) {
            for (int i = 0; i < childrenCount; i++) {
                View view = getChildAt(i);
                Point p = findPosition(i);
                int left = (itemWidth + spacing) * p.y;
                int top = (itemHeight + spacing) * p.x;
                int right = left + itemWidth;
                int bottom = top + itemHeight;
                view.layout(left, top, right, bottom);
            }
        }
    }


    public int getSpacing() {
        return spacing;
    }

    public void setSpacing(int spacing) {
        this.spacing = spacing;
    }

    /**
     * 获取子View的宽
     */
    public int getItemWidth() {
        return itemWidth;
    }

    /**
     * 获取子View的高
     */
    public int getItemHeight() {
        return itemHeight;
    }

    public void setAdapter(BaseAdapter adapter) {
        if (mAdapter != null) {
            mAdapter.unregisterDataSetObserver(mObserver);
        }
        removeAllViews();
        mAdapter = adapter;
        if (mAdapter != null) {
            mAdapter.registerDataSetObserver(mObserver);
            mAdapter.notifyDataSetInvalidated();
        }
    }

    public BaseAdapter getAdapter() {
        return mAdapter;
    }

    public void bindLinearLayout() {
        removeAllViews();
        int count = mAdapter.getCount();
        for (int i = 0; i < count; i++) {
            View v = mAdapter.getView(i, null, null);
            final int position = i;
            if (mOnItemClickListener != null) {
                v.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        mOnItemClickListener.onItemClick(null, v, position, 0L);
                    }
                });
            }
            addView(v, i);
        }
    }

    public void setOnItemClickListener(AdapterView.OnItemClickListener listener) {
        mOnItemClickListener = listener;
    }

    private DataSetObserver mObserver = new DataSetObserver() {
        @Override
        public void onChanged() {
            bindLinearLayout();
        }

        @Override
        public void onInvalidated() {
            bindLinearLayout();
        }
    };


    /**
     * 获取Item所在的行列位置
     */
    private Point findPosition(int childNum) {
        Point p = new Point(0, 0);
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < columns; j++) {
                if ((i * columns + j) == childNum) {
                    p.x = i;//行
                    p.y = j;//列
                    break;
                }
            }
        }
        return p;
    }

    /**
     * 获取行列数
     */
    private void getTableInfo() {
        int length = getChildCount();
        if (length <= 3) {
            rows = 1;
            columns = length;
        } else if (length <= 6) {
            rows = 2;
            columns = 3;
            if (length == 4) {
                columns = 2;
            }
        } else {
            rows = 3;
            columns = 3;
        }
    }

    private int dpTpPx(float value) {
        DisplayMetrics dm = getResources().getDisplayMetrics();
        return (int) (TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, dm) + 0.5);
    }
}
